import { DictionaryType, requestDict } from "../../../common/dictionary/dictionary-type.js";
import certRegsApi from '../../../common/api/food/certregs.api.js';
import { uploadFile, requestFilePath, publicFileDraw, sliceFileName } from "../../../common/api/file-request.js";
import doT from '../../../../vendor/template/doT.js';
import { Select2Page } from "../../../common/serve-request.js";


(function (window, document, $) {
    let _vm, getReceveEntry = [];
    let addressindex = 0,editintentionCity, editintentionArr;

    $(function () {
        _vm = new Vue({
            el: "#recevEntries-form",
            data() {
                return {
                    entries: [{
                        "certTktNo": "",
                        "certTktCarNo": "",
                        "certTktNum": "",
                        "certTktDptrPlc": "",
                        "address": "",
                        "certTktIssueTime": ""
                    }],
                }
            },
            mounted() {
                let url = location.href
                let params = {} // url参数
                for (let key of (new URL(url)).searchParams.entries()) {
                    key[1] ? params[key[0]] = key[1] : ''
                }
                if (params.isEdit == 'true') {
                    document.title = '生猪入场与宰前检验分录 - 编辑'
                }
            },
            methods: {
                // 保存
                submit() {
                    let { certTktNo, certTktDptrPlc, certTktIssueTime, certTktNum, certTktCarNo, } = _vm.entries[0]
                    if (!Utils.IsNotNull(certTktNo)) {
                        return $.toptip(`请输入合格证编号!`, 'warning');
                    }
                    if (!(/^.{10}$/).test(certTktNo)) {
                        return $.toptip(`合格证编号必须为10位字符!`, 'warning');
                    }
                    if (!Utils.IsNotNull(certTktDptrPlc)) {
                        return $.toptip(`请选择启运地点!`, 'warning');
                    }
                    if (!Utils.IsNotNull(certTktIssueTime)) {
                        return $.toptip(`请选择签发日期!`, 'warning');
                    }
                    if (!Utils.IsNotNull(certTktNum)) {
                        return $.toptip(`请输入数量!`, 'warning');
                    }
                    if (!(/^\d+$/).test(certTktNum)) {
                        return $.toptip(`扣分为非负整数!`, 'warning');
                    }
                    if (!Utils.IsNotNull(certTktCarNo)) {
                        return $.toptip(`请输入车牌号!`, 'warning');
                    }
                    if (!(/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/).test(certTktCarNo)) {
                        return $.toptip(`请输入正确的车牌!`, 'warning');
                    }
                    savetips({ ..._vm.entries[0] })
                }
            }
        });
        $(document).on('mousedown', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $(document).on('focus', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
        _initcityPicker();
        _initCommand();

    });

    // 初始化数据
    const _initCommand = async () => {
        getReceveEntry = JSON.parse(Utils.GetSessionStorage("getReceveEntry")) || [];
        let isEdit = JSON.parse(getUrlKey('isEdit'))
        let seqId = getUrlKey('index')
        let getMainInfo = JSON.parse(Utils.GetSessionStorage("deliverDatas"));
        let carNo = getMainInfo.carNo;
        if(carNo){
            _vm.entries[0].certTktCarNo = carNo;
            $('#certTktCarNo').val(carNo);
        }

        // 编辑时赋值
        if (isEdit) {
            let datas = getReceveEntry.find(item => item.seq == seqId)
            const propertiesToCopy = [
                "certTktNo","certTktCarNo","certTktNum","certTktDptrPlc","address",
                "certTktIssueTime"
            ];
            propertiesToCopy.reduce((obj, prop) => {
                _vm.entries[0][prop] = datas[prop];
            }, {});
            if(Utils.IsNotNull(_vm.entries[0].certTktIssueTime)){
                _vm.entries[0].certTktIssueTime = moment(_vm.entries[0].certTktIssueTime).format('YYYY-MM-DD');
            }
        }

        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            location.href = `../certregs/addcertregs.html?v=${Utils.GetTime()}`;
        });

        // 选择评分日期
        $('#certTktIssueTime').on('click', function () {
            picktimeLimit();
        });

    }

    // 日期选择器
    const picktimeLimit = () => {
        weui.datePicker({
            defaultValue: (moment(new Date()).format('YYYY-MM-DD')).split('-'),
            end: moment(new Date()).format('YYYY-MM-DD'),
            className: 'mypick',
            onConfirm: async function (result) {
                let value = `${result[0].value}-${result[1].value}-${result[2].value}`;
                _vm.entries[0].certTktIssueTime = moment(new Date(value)).format('YYYY-MM-DD')
            }
        });
    }

    // 保存提示
    const savetips = (data) => {
        let savetype
        if (Utils.IsNotNull(getUrlKey("isEdit"))) {
            savetype = '修改'
        }
        else {
            savetype = '保存'
        }

        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
    				<div class="" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
    					<div>是否确认${savetype}该分录？</div>
    				</div>`,
            buttons: [
                {
                    text: "取消", className: "default", onClick: function () {
                        $.closeModal();
                    }
                },
                {
                    text: "保存", onClick: function () {
                        let seq = parseInt(getUrlKey('index'))
                        let isEdit = JSON.parse(getUrlKey('isEdit'))
                        // 新增
                        if (!isEdit) {
                            getReceveEntry.push(data)
                        }
                        // 编辑
                        else if (isEdit) {
                            getReceveEntry[seq] = data
                        }
                        getReceveEntry.map((item, index) => {
                            item.seq = index
                        })
                        // 存入SessionStorage
                        JSON.stringify(Utils.SetSessionStorage("getReceveEntry", getReceveEntry))
                        location.href = `./addcertregs.html?v=${Utils.GetTime()}`;
                        $.closeModal();
                    }
                }
            ]
        });
    }

    // 获取地址栏的参数
    const getUrlKey = (name) => {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }
    //解决字段过长问题
    const cutstr = (str, len) => {
        var str_length = 0;
        var str_len = 0;
        var str_cut = new String();
        str_len = str.length;
        for (var i = 0; i < str_len; i++) {
            var a = str.charAt(i);
            str_length++;
            if (escape(a).length > 4) {
                //中文字符的长度经编码之后大于4 
                str_length++;
            }
            str_cut = str_cut.concat(a);
            if (str_length >= len) {
                str_cut = str_cut.concat("...");
                return str_cut;
            }
        }
        //如果给定字符串小于指定长度，则返回源字符串； 
        if (str_length < len) {
            return str;
        }
    }

    function unique(arr) {
        const res = new Map();
        return JSON.parse(JSON.stringify(arr)).filter((a) => !res.has(a.id) && res.set(a.id, 1))
    }

    // 初始化发货行政区划
    const _initcityPicker = () => {
        // 取消按钮
        $('#canvalBtn').on('click', function () {
            $('#maskback').css('display', 'none')
            document.body.style.overflow = 'scroll'
            document.body.style.position = 'relative'

        })
        // 确定按钮
        $('#determineBtn').on('click', function () {
            let selectArr = []
            $('#selectCity').find('.innerAddress').each((index, item) => {
                let selectAddresss = $(item).text()
                if (Utils.IsNotNull(selectAddresss) && selectAddresss != '请选择') {
                    selectArr.push(selectAddresss)
                }
            })

            let selectIdArr = []
            $('#selectCity').find('.adressId').each((index, item) => {
                let selectAddresssId = $(item).text()
                if (Utils.IsNotNull(selectAddresssId)) {
                    selectIdArr.push(selectAddresssId)
                }
            })
            if (!Utils.IsNotNull(selectArr[0])) {
                $.toptip(`请选择省!`, 'warning');
                return
            }
            else if (!Utils.IsNotNull(selectArr[1])) {
                $.toptip(`请选择市!`, 'warning');
                return
            }
            else if (!Utils.IsNotNull(selectArr[2])) {
                $.toptip(`请选择区县!`, 'warning');
                return
            }
            else {
                let  certTktDptrPlcId = `${selectIdArr.join(';')}|${selectArr.join(';')}`
                let selectCity = selectArr.join('-')
                $('#certTktDptrPlc').val(selectCity)
                _vm.entries[0].certTktDptrPlc = selectCity;
                editintentionCity = selectCity
                $('#canvalBtn').click()
            }
        })
        // 点击灰色遮罩层
        $('#unimportmask').on('click', function () {
            $('#canvalBtn').click()
        })
        // 点击发货行政区划
        $('#search-intentionCity').on('click', function () {
            editintentionCity = $('#certTktDptrPlc').val() || []
            // 关闭键盘
            document.activeElement.blur();
            // body禁止滚动
            document.body.style.position = 'fixed'
            document.body.style.overflow = 'hidden'
            // 清空选择页面内容
            $('#intentionContain').children('div').eq(0).empty()
            $('.innerAddress,.adressId').text('')
            changeStyle(0)

            addressindex = 0
            getAddress('province', "e8wa").then(res => {
                if (Utils.IsNotNull(editintentionCity)) {
                    editintentionArr = editintentionCity.split('-')
                    let editaddress = res.filter(item => {
                        return item.name == editintentionArr[0]
                    })
                    if (Utils.IsNotNull(editaddress)) {
                        $(`#${editaddress[0].id}`).click()
                    }
                }
            })
            setTimeout(() => {
                $('#maskback').css('display', 'block')
            }, 200);
        })
        // 点击导航栏
        $('#selectCity').on('click', 'li', function () {
            editintentionArr = []
            $(this).addClass('activeStyle').siblings('li').removeClass('activeStyle')
            $(this).find('.uderline').addClass('underlineit')
            $(this).siblings('li').find('.uderline').removeClass('underlineit')
            addressindex = $(this).index()
            $('#intentionContain').children('div').eq(addressindex).css('display', 'block').siblings('div').css('display', 'none')
        })
        // 选择之后
        $(document).on('click', '.addressCon', async function () {
            let addressid = $(this).attr('id')
            let addressName = $(this).text()
            $('#selectCity').find('li').eq(addressindex).find('span').text(addressName)
            $('#selectCity').find('li').eq(addressindex).find('.adressId').text(addressid)

            $(this).addClass('activeStyle').siblings('div').removeClass('activeStyle')
            addressindex = addressindex + 1
            changeStyle(addressindex)
            $('#intentionContain').children('div').eq(addressindex).empty()
            $('#intentionContain').children('div').eq(addressindex).last().nextAll().empty()
            $('#selectCity').find('li').eq(addressindex).find('span').parent().last().nextAll().find('.innerAddress').text('')

            if (addressindex == 1) {
                getAddress('city', addressid).then(res => {
                    if (Utils.IsNotNull(editintentionArr) && Utils.IsNotNull(editintentionArr[1])) {
                        let editaddress = res.filter(item => {
                            return item.name == editintentionArr[1]
                        })
                        if (Utils.IsNotNull(editaddress)) {
                            $(`#${editaddress[0].id}`).click()
                        }
                    }
                })
                let nextNav = $('#selectCity').find('li').eq(addressindex + 1).find('span')
                if (Utils.IsNotNull(nextNav.text())) {
                    nextNav.text('')
                }
            }
            else if (addressindex == 2) {
                getAddress('district', addressid).then(res => {
                    if (Utils.IsNotNull(editintentionArr) && Utils.IsNotNull(editintentionArr[2])) {
                        let editaddress = res.filter(item => {
                            return item.name == editintentionArr[2]
                        })
                        if (Utils.IsNotNull(editaddress)) {
                            $(`#${editaddress[0].id}`).click()
                        }
                    }
                })
            }
            else if (addressindex == 3) {
                getAddress('street', addressid).then(res => {
                    if (Utils.IsNotNull(editintentionArr) && Utils.IsNotNull(editintentionArr[2])) {
                        let editaddress = res.filter(item => {
                            return item.name == editintentionArr[3]
                        })
                        if (Utils.IsNotNull(editaddress)) {
                            $(`#${editaddress[0].id}`).click()
                        }
                    }
                })
            }
            else if (addressindex > 3) {
                $('#selectCity').find('li').eq(3).find('span').text(addressName)
            }
        })
    }
    const changeStyle = (id) => {
        $('#selectCity').find('li').eq(id).find('span').text('请选择')
        $('#selectCity').find('li').eq(id).addClass('activeStyle').siblings('li').removeClass('activeStyle')
        $('#selectCity').find('li').eq(id).find('.uderline').addClass('underlineit')
        $('#selectCity').find('li').eq(id).siblings('li').find('.uderline').removeClass('underlineit')
    }
    // 获取地点 联动
    const getAddress = async (level, pid) => {
        return new Promise((resolve, reject) => {
            let addressQuery = {
                level: level,
                pid: pid
            }
            getDistory(addressQuery).then(res => {
                let addressData = [...res]
                $('#intentionContain').children('div').eq(addressindex).css('display', 'block').siblings('div').css('display', 'none')
                addressData.forEach(item => {
                    $('#intentionContain').children('div').eq(addressindex).append(`<div class="addressCon" id="${item.id}" style="margin-bottom:8px">${item.name}</div>`)
                })
                resolve(addressData)
            })
        })
    }

    //获取行政区划 
    const getDistory = (data) => {
        return new Promise((resolve, reject) => {
            $.ajax({
                "url": `${Utils.CurDomain.SubDataUrl}/districts/q?l=${data.level}&pid=${data.pid}`,
                "type": 'GET',
                "dataType": "json",
                "beforeSend": Utils.AjaxBeforeSend,
                "success": function (result) {
                    resolve(result.data)
                },
                "error": function (xhr, textStatus, errorThrown) {
                    Utils.AjaxError(xhr, textStatus, errorThrown)
                }
            });
        })
    }



})(window, document, jQuery)